package com.luoqiuy.poet.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import java.util.concurrent.Callable;

public class UploadFile implements Callable<String> {

    private MultipartFile file;

    private static final String FILE_UPLOAD_PATH= "D:/poet/src/main/resources/static/img/head/";
    private Logger log = LoggerFactory.getLogger(UploadFile.class);

    public UploadFile(MultipartFile file) {
        this.file = file;
    }

    @Override
    public String call(){
        if (file.isEmpty()){
            return null;
        }
        String fileName = this.file.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        //生成文件名
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
        Random r = new Random();
        StringBuilder tempName = new StringBuilder();
        tempName.append(sdf.format(new Date())).append(r.nextInt(100)).append(suffix);
        String newFileName = tempName.toString();
        try {
            byte[] bytes = file.getBytes();
            Path path = Paths.get(FILE_UPLOAD_PATH + newFileName);
            Files.write(path, bytes);
            return (FILE_UPLOAD_PATH + newFileName).substring((FILE_UPLOAD_PATH + newFileName).lastIndexOf("/img"));
        }catch (Exception e){
            log.warn(e.toString());
            log.warn("upload headImg failed");
            return null;
        }
    }
}
